
package botlab;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 *
 * @author Quentin
 */
public class CallBackManager
{
    private static final CallBackManager instance = new CallBackManager();
    HashMap<String,ArrayList<Runnable>> callBacks;

    public CallBackManager()
    {
        callBacks = new HashMap<String, ArrayList<Runnable>>();
    }
    
    public static CallBackManager getInstance()
    {
        return instance;
    }
    
    public void addTask(String name,Runnable task)
    {
        if(callBacks.containsKey(name))
        {
            callBacks.get(name).add(task);
        }
        else
        {
            ArrayList l = new ArrayList<Runnable>();
            l.add(task);
            callBacks.put(name,l);
        }
    }
    
    public void actionPerformed(String name) throws Exception
    {
        if(this.callBacks.containsKey(name))
        {
            ArrayList<Runnable> tasks = this.callBacks.get(name);
            for(Iterator<Runnable> it = tasks.iterator();it.hasNext();)
            {
                it.next().run();
            }
            tasks.clear();
            this.callBacks.remove(name);
        }
        else
            throw new Exception("No callBack corresponding to this name : "+name);
        
    }
    
}
